package com.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

public class UserInterceptor implements HandlerInterceptor
{
    @Override
    public boolean preHandle( HttpServletRequest req , HttpServletResponse resp , Object o )
            throws Exception
    {
        //将默认访问许可路径加入集合
        ArrayList<String> defaultPremitUrlList = new ArrayList<>();
        defaultPremitUrlList.add( "toLoginPage" );
        defaultPremitUrlList.add( "dologin" );
        defaultPremitUrlList.add( "exit");
        //获取请求路径
        String fullReqUri = req.getRequestURI();
        //System.out.println( fullReqUri );
        String reqUri = fullReqUri.substring( fullReqUri.lastIndexOf( "/" ) + 1 );
        //System.out.println( reqUri );
        HttpSession session = req.getSession();
        //若请求的是默认许可访问路径 放行
        if( defaultPremitUrlList.contains( reqUri ))
        {
            return true;
        }
        //请求的为非默认许可访问路径
        else
        {
            //获取当前访问用户
            Object obj = session.getAttribute( "user" );
            //若用户已登录
            if( obj != null )
            {
                //从session中取出用户具有的可访问路径
                ArrayList<String> userUrlList = (ArrayList<String>)session.getAttribute( "userUrlList" );
                //System.out.println( userUrlList );
                if( userUrlList != null && userUrlList.contains( reqUri ) )
                    return true;
                else
                {
                    System.out.println("权限不足");
                    resp.sendRedirect( "/noPremission.jsp" );
                    return false;
                }
            }
            //若用户未登录重定向到登陆页面
            else
                resp.sendRedirect( "/do/toLoginPage" );
        }
        return false;
    }

    @Override
    public void postHandle( HttpServletRequest req , HttpServletResponse resp ,
                            Object o , ModelAndView modelAndView ) throws Exception
    { }

    @Override
    public void afterCompletion( HttpServletRequest req , HttpServletResponse resp ,
                                 Object o , Exception e ) throws Exception
    { }
}
